//
//  CXClickGiftViewController.m
//  GiftThat
//
//  Created by ChuXiang on 16/1/10.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "CXClickGiftViewController.h"
#import "LJFModel.h"
#import "LJFHotCollectionViewCell.h"
#import "LJFNewHotViewController.h"
#import "MLKMenuPopover.h"

#define MENU_POPOVER_FRAME  CGRectMake(self.view.width - 148, 0, 140, 176)

//-------刷新
//限制一次刷新
static int scrolltimes = 0;
//现在数据个数
static int numOfAll = 0;
//-------
static int oldNumOfAll = 0;
//判断右Button是否出现
static BOOL hideOrApper = YES;


@interface CXClickGiftViewController () <UICollectionViewDelegate, UICollectionViewDataSource, MLKMenuPopoverDelegate>
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSMutableArray *muArray;

@property(nonatomic,strong) MLKMenuPopover *menuPopover;
@property(nonatomic,strong) NSArray *menuItems;
@property (nonatomic, copy) NSString *getDataUrl;
//-------刷新
//tableview方向判断
@property (nonatomic, assign) CGFloat contenty;


@end

@implementation CXClickGiftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = self.collectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    
    self.navigationItem.title = [self.getData lastObject];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"< 返回" style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonDidPress:)];

    [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"FZLanTingHei-EL-GBK" size:18],NSForegroundColorAttributeName:[UIColor whiteColor]} forState:UIControlStateNormal];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"Sort"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonDidPress:)];
    
    self.muArray = [NSMutableArray array];
    self.menuItems = [NSArray arrayWithObjects:@"默认排序", @"按热度排序", @"价格从低到高", @"价格从高到低", nil];
    
}


- (void)setGetData:(NSArray *)getData {
    if (_getData != getData) {
        _getData = getData;
    }
    
    self.getDataUrl = [getData firstObject];
    [self getDataWithUrl:self.getDataUrl];


    [self creatCollectionView];
}

#pragma mark - GetData
-(void)getDataWithUrl:(NSString *)url {

    
    
    [CXNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        if (result) {
            NSDictionary *dic = result;
            NSDictionary *dic1 = [dic objectForKey:@"data"];
            NSArray *array = [dic1 objectForKey:@"items"];
            for (NSDictionary *dic2 in array) {
                LJFModel *hot = [[LJFModel alloc] initWithDictionary:dic2];
                
                [self.muArray addObject:hot];
            }
            scrolltimes = 0;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        }
        
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
}

#pragma mark - CreateCollectionView
-(void)creatCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width - 10)/2,200);
    
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, 0, self.view.frame.size.width - 10, self.view.frame.size.height - 113) collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[LJFHotCollectionViewCell class] forCellWithReuseIdentifier:@"NewCollectionViewCell"];
    
    [self.view addSubview:self.collectionView];
    
    
}

#pragma mark - CollectionViewDataSource
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    LJFHotCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NewCollectionViewCell" forIndexPath:indexPath];
    if (self.muArray.count > indexPath.item) {
        cell.ljfmodel = self.muArray[indexPath.item];
    }
    return cell;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.muArray.count;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    LJFModel *model = [[LJFModel alloc]init];
    if (self.muArray.count > indexPath.item) {
        model = self.muArray[indexPath.item];
        LJFNewHotViewController *new = [[LJFNewHotViewController alloc]init];
//        new.ljfmodel = self.muArray[indexPath.item];
        new.urlString = model.url;
        [self.navigationController pushViewController:new animated:YES];
    }
}


#pragma mark - LeftButtonDidPress
- (void)leftButtonDidPress:(UIBarButtonItem *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - RightButtonDidPress
- (void)rightBarButtonDidPress:(UIBarButtonItem *)sender {
    
    if (hideOrApper) {
        [self.menuPopover dismissMenuPopover];
        
        self.menuPopover = [[MLKMenuPopover alloc] initWithFrame:MENU_POPOVER_FRAME menuItems:self.menuItems];
        
        self.menuPopover.menuPopoverDelegate = self;
        [self.menuPopover showInView:self.view];
    }else {
        [self.menuPopover dismissMenuPopover];
    }
    hideOrApper = !hideOrApper;
}

#pragma mark - 右button选择框代理方法
- (void)menuPopover:(MLKMenuPopover *)menuPopover didSelectMenuItemAtIndex:(NSInteger)selectedIndex{
    hideOrApper = !hideOrApper;

    [self.muArray removeAllObjects];
    [self.menuPopover dismissMenuPopover];
    if (selectedIndex == 0) {
        numOfAll = 0;
        oldNumOfAll = 0;
        [self getDataWithUrl:[self.getData firstObject]];
        [self.collectionView reloadData];
        
    }else if (selectedIndex == 1) {
        numOfAll = 0;
        oldNumOfAll = 0;
        self.getDataUrl = [NSString stringWithFormat:@"%@&sort=hot",[self.getData firstObject]];
        [self getDataWithUrl:self.getDataUrl];
        [self.collectionView reloadData];
    }else if (selectedIndex == 2) {
        numOfAll = 0;
        oldNumOfAll = 0;
        self.getDataUrl = [[self.getData firstObject] stringByAppendingString:@"&sort=price%3Aasc"];
        [self getDataWithUrl:self.getDataUrl];
        [self.collectionView reloadData];
        
    }else if (selectedIndex == 3) {
        numOfAll = 0;
        oldNumOfAll = 0;
        self.getDataUrl = [[self.getData firstObject] stringByAppendingString:@"&sort=price%3Adesc"];
        [self getDataWithUrl:self.getDataUrl];
        [self.collectionView reloadData];
    }
}
#pragma mark - 上拉加载
-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > self.contenty) {
        if (scrollView.contentOffset.y > scrollView.contentSize.height - 700) {
            //加载更多数据
            if (scrolltimes == 0) {
                numOfAll += 20;
                NSString *str = [NSString stringWithFormat:@"offset=%d", oldNumOfAll];
                NSString *str1 = [NSString stringWithFormat:@"offset=%d",numOfAll];
                self.getDataUrl = [self.getDataUrl stringByReplacingOccurrencesOfString:str withString:str1];
                [self getDataWithUrl:self.getDataUrl];
                scrolltimes = 1;
                oldNumOfAll = numOfAll;
            }
        }
    }
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
